package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户提醒设置控制器
 */
@Slf4j
@Tag(name = "用户提醒设置", description = "用户饮水提醒相关设置接口")
@RestController
@RequestMapping("/api/user/reminder")
public class UserReminderController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户提醒设置
     */
    @Operation(summary = "获取用户提醒设置", description = "获取用户当前的饮水提醒设置")
    @GetMapping("/settings/{userId}")
    public RestApiResponse<Map<String, Object>> getReminderSettings(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            Map<String, Object> settings = new HashMap<>();
            settings.put("reminderEnabled", user.getReminderEnabled() == 1);
            settings.put("reminderInterval", user.getReminderInterval());
            settings.put("wxOpenidBound", user.getWxOpenid() != null && !user.getWxOpenid().isEmpty());
            
            return RestApiResponse.ok("获取提醒设置成功", settings);
            
        } catch (Exception e) {
            log.error("获取用户提醒设置异常: userId={}", userId, e);
            return RestApiResponse.businessError("50002", "获取提醒设置失败: " + e.getMessage());
        }
    }

    /**
     * 开启/关闭饮水提醒
     */
    @Operation(summary = "开启/关闭饮水提醒", description = "用户可以选择开启或关闭定时饮水提醒")
    @PostMapping("/toggle/{userId}")
    public RestApiResponse<Boolean> toggleReminder(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "是否开启提醒", required = true) @RequestParam Boolean enabled) {
        
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            // 检查是否绑定了公众号
            if (enabled && (user.getWxOpenid() == null || user.getWxOpenid().isEmpty())) {
                return RestApiResponse.businessError("50003", "请先绑定微信公众号才能开启提醒功能");
            }
            
            // 更新提醒设置
            User updateUser = new User();
            updateUser.setId(userId);
            updateUser.setReminderEnabled(enabled ? 1 : 0);
            updateUser.setUpdatedAt(LocalDateTime.now());
            
            boolean result = userService.updateById(updateUser);
            
            if (result) {
                log.info("用户{}饮水提醒功能: userId={}", enabled ? "开启" : "关闭", userId);
                return RestApiResponse.ok(enabled ? "饮水提醒已开启" : "饮水提醒已关闭", true);
            } else {
                return RestApiResponse.businessError("50002", "设置失败");
            }
            
        } catch (Exception e) {
            log.error("切换用户提醒设置异常: userId={}, enabled={}", userId, enabled, e);
            return RestApiResponse.businessError("50002", "设置提醒失败: " + e.getMessage());
        }
    }

    /**
     * 设置提醒间隔
     */
    @Operation(summary = "设置提醒间隔", description = "设置饮水提醒的时间间隔(分钟)")
    @PostMapping("/interval/{userId}")
    public RestApiResponse<Boolean> setReminderInterval(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId,
            @Parameter(description = "提醒间隔(分钟)", required = true) @RequestParam Integer intervalMinutes) {
        
        try {
            if (intervalMinutes < 30 || intervalMinutes > 480) {
                return RestApiResponse.businessError("50004", "提醒间隔必须在30分钟到8小时之间");
            }
            
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            // 更新提醒间隔
            User updateUser = new User();
            updateUser.setId(userId);
            updateUser.setReminderInterval(intervalMinutes);
            updateUser.setUpdatedAt(LocalDateTime.now());
            
            boolean result = userService.updateById(updateUser);
            
            if (result) {
                log.info("用户设置提醒间隔: userId={}, interval={}分钟", userId, intervalMinutes);
                return RestApiResponse.ok("提醒间隔设置成功", true);
            } else {
                return RestApiResponse.businessError("50002", "设置失败");
            }
            
        } catch (Exception e) {
            log.error("设置用户提醒间隔异常: userId={}, interval={}", userId, intervalMinutes, e);
            return RestApiResponse.businessError("50002", "设置提醒间隔失败: " + e.getMessage());
        }
    }

    /**
     * 获取提醒统计信息
     */
    @Operation(summary = "获取提醒统计信息", description = "获取用户的提醒相关统计信息")
    @GetMapping("/stats/{userId}")
    public RestApiResponse<Map<String, Object>> getReminderStats(
            @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
        
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("reminderEnabled", user.getReminderEnabled() == 1);
            stats.put("reminderInterval", user.getReminderInterval());
            stats.put("isWxBound", user.getWxOpenid() != null && !user.getWxOpenid().isEmpty());
            stats.put("lastLoginTime", user.getLastLoginTime());
            
            // 统计今日应该发送的提醒次数（基于定时任务）
            int dailyRemindersCount = 4; // 早上、中午、晚上、睡前
            stats.put("dailyRemindersCount", dailyRemindersCount);
            
            return RestApiResponse.ok("获取提醒统计成功", stats);
            
        } catch (Exception e) {
            log.error("获取用户提醒统计异常: userId={}", userId, e);
            return RestApiResponse.businessError("50002", "获取统计信息失败: " + e.getMessage());
        }
    }
} 